package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginFilter")//标志 拦截器
public class LoginCheckFilter implements Filter {
    //匹配路径
    final AntPathMatcher pathMatcher = new AntPathMatcher();
    //把需要拦截的路径存到数组中方便使用
    private String[] authUrl = new String[]{
            "/favicon.ico",
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/sendMsg",
            "/user/login",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //这里我们加了一句话 获取线程的ID
        log.info("loginCheckFilter...开启了,获取线程ID:{}",Thread.currentThread().getId());
        //过滤器的处理逻辑
        //强转成http 因为我们需要获取url 是基于http协议
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取URI  得到URI
        String requestURI = request.getRequestURI();
        //打印日志
        log.info("请求路径:{}", requestURI);
        //3.首先判断如果不需要处理直接放行
        if (checkAuthUrl(requestURI)) {
            filterChain.doFilter(request, response);
            //如果放行了代码就不要在往下执行了 直接返回
            return;
        }
        //4.判断登录状态,如果已登录,则直接放行
        //如何判断用户是否登录 之前我们做过把登录过的用户存入了session中 所以直接利用这个判断就可以
        if (request.getSession().getAttribute("employee") != null) {
            //打印一下
            log.info("用户已登陆id:{}", request.getSession().getAttribute("employee"));
            //我们获取到登录的id 把他保存到了ThreadLocal
            Long userId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentID(userId);
            //到这里的话证明是登陆过  放行
            filterChain.doFilter(request, response);
            //如果放行了代码就不要在往下执行了 直接返回
            return;
        }
        // 移动端登录
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentID(userId);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("未登录授权!");
        //5.判断如果未登录则返回未登录结果
        //注意返回的信息，必须是NOTLOGIN，否则客户端无法跳转，因为前端检查是是字符串是否是NOTLOGIN
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    //定义方法遍历集合中的被拦截路径
    public boolean checkAuthUrl(String requestURI) {
        for (String url : authUrl) {
            //如果路径包含的话 就通过
            //if (requestURI.contains(url)) {
            //    return true;
            //}
            //以上写法不准确  准确写法正则写法 如下
            if (pathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
